1519D - Maximum Sum of Products - CodeForces Solution


brute force dp implementation math two pointers *1600

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL));
#define pb push_back
using namespace std;
const ll N = 5e3+2;
const ll MOD = 1e9 + 7;
ll n;
vector<vector<ll>> dp;
vector<vector<bool>> test[2];
vector<ll> a, b;
ll solve(ll i, ll j, bool state)
{
    if(i==n)
    {
        if(j==n)
            return 0;
        else
            return solve(i-1,j,false);
    }
    if(test[state][i][j]) return dp[i][j];
    ll ans = 0;
    if(!state)
    {
        if(i==j)
            ans = a[i]*b[j] + solve(i+1,j+1,false);
        else
        {
            ans = a[i]*b[j] + a[j]*b[i];
            if(i-1==j+1)
                ans += a[i-1]*b[j+1];
            if(i-1>j+1)
                ans += solve(i-1,j+1,false);
        }
    }
    else
    {
        if(i==j)
            ans = max(a[i]*b[j]+solve(i+1,j+1,true),solve(i+1,j,true));
        else
        {
            ans = solve(i+1,j,true);
            ll ans1 = a[i]*b[j] + a[j]*b[i];
            if(i-1==j+1)
                ans1 += a[i-1]*b[j+1];
            if(i-1>j+1)
                ans1 += solve(i-1,j+1,false);
            ans1 += solve(i+1,i+1,false);
            ans = max(ans, ans1);
        }
    }
    test[state][i][j] = true;
    return dp[i][j] = max(dp[i][j],ans);
}

int main()
{
    fastread();
    cin>>n;
    a.assign(n,0);
    b.assign(n,0);
    dp.assign(n,vector<ll>(n,-1));
    test[0].assign(n,vector<bool>(n,0));
    test[1].assign(n,vector<bool>(n,0));
    for(ll i = 0; i<n; i++)
        cin>>a[i];
    for(ll i = 0; i<n; i++)
        cin>>b[i];
    ll ans = solve(0,0, true);
    cout<<ans<<"\n";
    return 0;
}
/*
*/


Comments

Submit
0 Comments
More Questions

107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection
1665D - GCD Guess
29A - Spit Problem
1097B - Petr and a Combination Lock
92A - Chips
1665B - Array Cloning Technique
1665A - GCD vs LCM
118D - Caesar's Legions
1598A - Computer Game
1605A - AM Deviation
1461A - String Generation
1585B - Array Eversion
1661C - Water the Trees
1459A - Red-Blue Shuffle
1661B - Getting Zero
1661A - Array Balancing
1649B - Game of Ball Passing
572A - Arrays
1455A - Strange Functions
1566B - MIN-MEX Cut
678C - Joty and Chocolate
1352E - Special Elements
1520E - Arranging The Sheep
1157E - Minimum Array
1661D - Progressions Covering